package cn.bonoon.kernel.expression.resolver;

import java.lang.reflect.Method;

import cn.bonoon.kernel.expression.ExpressionParseContext;
import cn.bonoon.kernel.expression.results.FixedExpressionValue;

/**
 * 处理类的静态方法
 * 
 * @author jackson
 *
 */
public class FieldExpressionResolver extends AbstractExpressionPropertyResolver{

	FieldExpressionResolver() {
		super("FIELD");
	}

	@Override
	protected boolean internalResolver(ExpressionParseContext context, String[] commands) throws Exception{
		Class<?> cls = Class.forName(commands[1]);
		Object value = cls.getField(commands[2]).get(null);
		context.value(new FixedExpressionValue(context, internalResolveValue(cls, value, commands)));
		return super.internalResolver(context, commands);
	}

	private Object internalResolveValue(Class<?> cls, Object value, String[] commands) throws Exception{
		if(commands.length > 3){
			String methodName = commands[3];
			if(cls.isEnum()){
				if("name".equals(methodName)){
					return ((Enum<?>)value).name();
				}
				
				if("ordinal".equals(methodName)){
					value = ((Enum<?>)value).ordinal();
				}
			}else{
				Class<?> valueClass = value.getClass();
				Method method = valueClass.getMethod(methodName);
				value = method.invoke(value);
			}
		}
		
		return value;
	}
}
